
package com.chookss.home.audit.clockIn;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aliyun.svideo.common.utils.NetUtils;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.StaticClass;
import com.chookss.home.audit.AuditActivity;
import com.chookss.home.entity.ClockInEntity;
import com.chookss.home.entity.ClockInGroupEntity;
import com.chookss.home.entity.ClockInRulesEntity;
import com.chookss.home.entity.WorkNewEntity;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyToast;
import com.chookss.tools.NavigationTools;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.CircleImageView;
import com.chookss.view.DrawableTextView;
import com.chookss.view.InitDialog;
import com.chookss.view.InitEditDialog;
import com.chookss.view.listener.ShareDialogListener;
import com.chookss.view.listener.StudyDialogListener;
import com.google.gson.reflect.TypeToken;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.lvgroup.hospital.base.BaseAct;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnCancelListener;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.lxj.xpopup.interfaces.OnSelectListener;

import org.jetbrains.annotations.Nullable;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ClockInHomeActivity extends BaseAct {
//打卡首页

    @BindView(R.id.common_title_back)
    LinearLayout commonTitleBack;
    @BindView(R.id.ivHead)
    CircleImageView ivHead;
    @BindView(R.id.tvName)
    TextView tvName;
    @BindView(R.id.tvPost)
    TextView tvPost;
    @BindView(R.id.tvRules)
    TextView tvRules;
    @BindView(R.id.tvProject)
    TextView tvProject;
    @BindView(R.id.tvAm)
    TextView tvAm;
    @BindView(R.id.tvAmTime)
    TextView tvAmTime;
    @BindView(R.id.tvAmTimeInit)
    TextView tvAmTimeInit;
    @BindView(R.id.tvAmTimeType)
    TextView tvAmTimeType;
    @BindView(R.id.tvAmGroup)
    TextView tvAmGroup;
    @BindView(R.id.tvAmLoc)
    TextView tvAmLoc;
    @BindView(R.id.llAmLoc)
    LinearLayout llAmLoc;
    @BindView(R.id.tvAmSure)
    TextView tvAmSure;
    @BindView(R.id.tvPm)
    TextView tvPm;
    @BindView(R.id.tvPmTime)
    TextView tvPmTime;
    @BindView(R.id.tvPmTimeInit)
    TextView tvPmTimeInit;
    @BindView(R.id.tvPmTimeType)
    TextView tvPmTimeType;
    @BindView(R.id.tvPmGroup)
    TextView tvPmGroup;
    @BindView(R.id.tvPmLoc)
    TextView tvPmLoc;
    @BindView(R.id.llPmLoc)
    LinearLayout llPmLoc;
    @BindView(R.id.tvCurrentTime)
    TextView tvCurrentTime;
    @BindView(R.id.tvPmSure)
    TextView tvPmSure;
    @BindView(R.id.tvAmTimeField)
    TextView tvAmTimeField;
    @BindView(R.id.tvPmTimeField)
    TextView tvPmTimeField;
    @BindView(R.id.tvDate)
    TextView tvDate;
    @BindView(R.id.tvLoc)
    TextView tvLoc;
    @BindView(R.id.tvLocRefresh)
    TextView tvLocRefresh;
    @BindView(R.id.ivRefresh)
    ImageView ivRefresh;
    @BindView(R.id.tvProjectChoice)
    DrawableTextView tvProjectChoice;
    @BindView(R.id.tvAmNoData)
    TextView tvAmNoData;
    @BindView(R.id.tvPmNoData)
    TextView tvPmNoData;
    @BindView(R.id.llAmGroup)
    LinearLayout llAmGroup;
    @BindView(R.id.llPmGroup)
    LinearLayout llPmGroup;
    @BindView(R.id.ivAudit)
    ImageView ivAudit;
    public LocationClient mLocationClient = null;
    private MyLocationListener myListener = new MyLocationListener();
    private ClockInRulesEntity clockInRulesEntity = null;//打卡考勤组
    private List<ClockInGroupEntity> groupEntities = new ArrayList<>();
    private String[] groupArray = null;
    private ClockInEntity clockInEntity = null;//当天打卡信息
    private long currentTime = 0L;//服务器当前时间
    private Timer mTimer = null;
    private TimerTask mTimerTask = null;
    private String locAddress, locJd, locWd, yichangCd = "0", waiqinCd = "0";
    private boolean isCheat = false;//是否打卡作弊，默认没有作弊
    private boolean hasLocPermissions = false;//默认没有打卡权限
    private int needType = -1;//需要重新刷新打卡然后打卡的类型 1上班 0下班
    private String groupCode = "";
    private long locTime = 0l;//最近一次定位时间
    private RotateAnimation rotate = null;//图片旋转动画

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_click_in_home);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        NavigationTools.saveUseRecord(this, "1", "27");
        // 从资源文件ic_launcher.png中获取图形对象
        tvName.setText(new ShareUtils().getString(this, StaticClass.USER_NICKNAME, ""));
        tvPost.setText("(" + new ShareUtils().getString(this, StaticClass.POST, "") + ")");
        GlideUtils.loadAvatar(this, new ShareUtils().getString(this, StaticClass.USER_AVATAR_URL, ""), ivHead);
        if (NetUtils.isGPSEnabled(this)) {
            getPermissions(0);
            getRules();
            getGroupList();
            selectCurDakaInfo();
            rotate = new RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
            rotate.setInterpolator(new LinearInterpolator());
            rotate.setDuration(500);//设置动画持续周期
            rotate.setRepeatCount(2);//设置重复次数 //
            rotate.setFillAfter(true);//动画执行完后是否停留在执行完的状态 r
            rotate.setStartOffset(0);//执行前的等待时间
            getworkList();
        } else {
            showDialog();
        }
    }
    private void showDialog() {
        new XPopup.Builder(this)
                .isDestroyOnDismiss(true)
                .dismissOnTouchOutside(false)
                .asConfirm("提示", "定位服务未开启，请打开定位服务",
                        "取消", "去开启",
                        new OnConfirmListener() {
                            @Override
                            public void onConfirm() {
                                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                startActivity(intent);
                                finish();
                            }
                        }, new OnCancelListener() {
                            @Override
                            public void onCancel() {
                                finish();
                            }
                        }, false)
                .show();
    }
    private void startLoc() {
        //声明LocationClient类
        try {
            if (mLocationClient == null) {
                LocationClient.setAgreePrivacy(true);
                mLocationClient = new LocationClient(getApplicationContext());
                LocationClientOption option = new LocationClientOption();
                mLocationClient.registerLocationListener(myListener);
                option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
                option.setCoorType("bd09ll");
                option.setIsNeedAddress(true);
                option.setOpenGnss(true);
                option.setLocationNotify(true);
                option.setScanSpan(1000);
                mLocationClient.setLocOption(option);
            }
            if (mLocationClient != null) {
                mLocationClient.start();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void selectCurDakaInfo() {
        //当天打卡情况
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<ClockInEntity>>() {
        }.getType(), null, Urls.selectCurDakaInfo, SignUtils2.makeSignStr(null), false, new ObserverCallback<ClockInEntity>() {
            @Override
            public void onSuccess(ClockInEntity data) {
                if (data != null) {
                    clockInEntity = data;
                    if(tvAm==null){
                        return;
                    }
                    //上午
                    if (Utils.isNull(data.getStartTime())) {
                        tvAm.setBackgroundResource(R.drawable.shape_circle_f24719);
                        tvAmTime.setText("");
                        llAmGroup.setVisibility(View.GONE);
                        llAmLoc.setVisibility(View.GONE);
                        tvAmNoData.setVisibility(View.VISIBLE);
                    } else {
                        tvAm.setBackgroundResource(R.drawable.shape_circle_e5e5e5);
                        tvAmTime.setText("上班" + ClockInUtils.getMinutes(data.getStartTime()));
                        llAmGroup.setVisibility(View.VISIBLE);
                        llAmLoc.setVisibility(View.VISIBLE);
                        tvAmNoData.setVisibility(View.GONE);
                        tvAmSure.setSelected(true);
                    }
                    //下午
                    if (Utils.isNull(data.getEndTime())) {
                        tvPm.setBackgroundResource(R.drawable.shape_circle_f24719);
                        tvPmTime.setText("");
                        llPmGroup.setVisibility(View.GONE);
                        llPmLoc.setVisibility(View.GONE);
                        tvPmNoData.setVisibility(View.VISIBLE);
                    } else {
                        tvPm.setBackgroundResource(R.drawable.shape_circle_e5e5e5);
                        tvPmTime.setText("下班" + ClockInUtils.getMinutes(data.getEndTime()));
                        llPmGroup.setVisibility(View.VISIBLE);
                        llPmLoc.setVisibility(View.VISIBLE);
                        tvPmNoData.setVisibility(View.GONE);
                        tvPmSure.setSelected(true);
                    }
                    if (Utils.isNull(data.getItemGroupName())) {
                        tvAmGroup.setText("未知");
                    } else {
                        tvAmGroup.setText(data.getItemGroupName() + "(" + ClockInUtils.getGroupEnd(data.getItemGroupCode()) + ")");
                    }
                    if (Utils.isNull(data.getXiabanItemGroupName())) {
                        tvPmGroup.setText("未知");
                    } else {
                        tvPmGroup.setText(data.getXiabanItemGroupName() + "(" + ClockInUtils.getGroupEnd(data.getXiabanItemGroupCode()) + ")");
                    }
                    if ("1".equals(data.getWaiqinCd())) {
                        tvAmTimeField.setVisibility(View.VISIBLE);
                        if ("1".equals(data.getShangbanDakaType())) {
                            tvAmTimeType.setVisibility(View.GONE);
                        } else {
                            tvAmTimeType.setVisibility(View.VISIBLE);
                        }
                    } else {
                        tvAmTimeField.setVisibility(View.GONE);
                        tvAmTimeType.setVisibility(View.VISIBLE);
                    }
                    if ("1".equals(data.getXiabanWaiqinCd())) {
                        tvPmTimeField.setVisibility(View.VISIBLE);
                        if ("1".equals(data.getXiabanDakaType())) {
                            tvPmTimeType.setVisibility(View.GONE);
                        } else {
                            tvPmTimeType.setVisibility(View.VISIBLE);
                        }
                    } else {
                        tvPmTimeField.setVisibility(View.GONE);
                        tvPmTimeType.setVisibility(View.VISIBLE);
                    }
                    if (Utils.isNull(data.getShangbanDakaType())) {
                        tvAmTimeType.setText("未打卡");
                        tvAmTimeType.setTextColor(Color.parseColor("#9A9A9A"));
                        tvAmTimeType.setBackgroundResource(R.drawable.shape_e5e5e5_2);
                    } else {
                        tvAmTimeType.setText(ClockInUtils.getClockInType(data.getShangbanDakaType()));
                        tvAmTimeType.setTextColor(Color.parseColor("#FFFFFF"));
                        tvAmTimeType.setBackgroundResource(ClockInUtils.getClockInBg(data.getShangbanDakaType()));
                    }
                    if (Utils.isNull(data.getXiabanDakaType())) {
                        tvPmTimeType.setText("未打卡");
                        tvPmTimeType.setTextColor(Color.parseColor("#9A9A9A"));
                        tvPmTimeType.setBackgroundResource(R.drawable.shape_e5e5e5_2);
                    } else {
                        tvPmTimeType.setText(ClockInUtils.getClockInType(data.getXiabanDakaType()));
                        tvPmTimeType.setTextColor(Color.parseColor("#FFFFFF"));
                        tvPmTimeType.setBackgroundResource(ClockInUtils.getClockInBg(data.getXiabanDakaType()));
                    }
                    if (Utils.isNull(data.getDakaAddress())) {
                        tvAmLoc.setText("未知");
                    } else {
                        tvAmLoc.setText(data.getDakaAddress());
                    }
                    if (Utils.isNull(data.getXiabanDakaAddress())) {
                        tvPmLoc.setText("未知");
                    } else {
                        tvPmLoc.setText(data.getXiabanDakaAddress());
                    }
                    if (!Utils.isNull(data.getCurrentTime())) {
                        currentTime = ClockInUtils.getCurrentTime3(data.getCurrentTime());
                        tvDate.setText(Utils.changeCnDate(data.getCurrentTime()));
                        tvCurrentTime.setText(ClockInUtils.getCurrentTime2(currentTime));
                        if (mTimer == null) {
                            startTimer();
                        }

                    }
                }

            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void getRules() {
        //考勤基本数据
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<ClockInRulesEntity>>>() {
        }.getType(), null, Urls.selectMyKaoqinGroupList, SignUtils2.makeSignStr(null), false, new ObserverCallback<List<ClockInRulesEntity>>() {
            @Override
            public void onSuccess(List<ClockInRulesEntity> data) {
                if (data != null && data.size() > 0) {
                    if(tvAmTimeInit==null){
                        return;
                    }
                    clockInRulesEntity = data.get(0);
                    if (!Utils.isNull(clockInRulesEntity.getGroupName())) {
                        if (clockInRulesEntity.getKaoqinRules().size() > 0) {
                            tvAmTimeInit.setText("(要求时间" + clockInRulesEntity.getKaoqinRules().get(0).getStartTime() + ")");
                            tvPmTimeInit.setText("(要求时间" + clockInRulesEntity.getKaoqinRules().get(0).getEndTime() + ")");
                        }

                    }
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void getGroupList() {
        //项目组基本数据
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<ClockInGroupEntity>>>() {
        }.getType(), null, Urls.selectMyItemGroupList, SignUtils2.makeSignStr(null), false, new ObserverCallback<List<ClockInGroupEntity>>() {
            @Override
            public void onSuccess(List<ClockInGroupEntity> data) {
                if (data != null && data.size() > 0) {
                    if(tvProject==null){
                        return;
                    }
                    groupEntities.addAll(data);
                    groupArray = new String[groupEntities.size()];
                    for (int i = 0; i < groupEntities.size(); i++) {
                        if ("1".equals(groupEntities.get(i).getMainCd())) {
                            groupArray[i] = groupEntities.get(i).getGroupName() + "[常驻]";
                        } else {
                            groupArray[i] = groupEntities.get(i).getGroupName();
                        }

                    }
                    if (!Utils.isNull(groupEntities.get(0).getGroupName())) {
                        tvProject.setText(groupEntities.get(0).getGroupName() + "(" + ClockInUtils.getGroupEnd(groupEntities.get(0).getGroupCode()) + ")");
                        groupCode = groupEntities.get(0).getGroupCode();
                    }

                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void insertDakaInfo(int type, String remark) {
        //打卡1上班0下班
        if (groupArray == null) {
            MyToast.show("项目组不能为空，请联系管理员后重试");
            return;
        }
        if (clockInEntity == null || clockInRulesEntity == null) {
            MyToast.show("考勤组不能为空，请联系管理员后重试");
            return;
        }
        if (Utils.isNull(locJd) || Utils.isNull(locWd) || Utils.isNull(locAddress)) {
            MyToast.show("定位失败，请退出页面重试");
            return;
        }
        Map<String, String> map = new HashMap<>();
        if (Utils.isNull(groupCode)) {
            MyToast.show("所在项目组不能为空，请联系管理员后重试");
            return;
        }
        map.put("itemGroupCode", groupCode);
        if (!Utils.isNull(clockInEntity.getStartTime())) {
            map.put("startTime", clockInEntity.getStartTime());
        }
        if (!Utils.isNull(clockInEntity.getId())) {
            map.put("id", clockInEntity.getId());
        }
        //上班卡不打，下午卡怎么办，没有id
        map.put("shangbanCd", type + "");
        map.put("dakaJd", locJd);
        map.put("dakaWd", locWd);
        map.put("yichangCd", yichangCd);
        map.put("waiqinCd", waiqinCd);
        map.put("dakaAddress", locAddress);
        if (!Utils.isNull(remark)) {
            if (1 == type) {
                map.put("shangbanWaiqinRemark", remark);
            } else {
                map.put("xiabanWaiqinRemark", remark);
            }
        }
        String url = "";
        if (1 == type) {
            url = Urls.insertDakaInfo;
        } else {
            url = Urls.insertXiabanDakaInfo;
        }
        showLoading();
        MyHttpRequest.getDefault().postRequestCompat(null, url, SignUtils2.makeSignStr(map), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) throws Exception {
                JSONObject reObject = new JSONObject(data);
                dismissLoading();
                if ("200".equals(reObject.getString("code"))) {
                    JSONObject reObject1 = reObject.getJSONObject("data");
                    if(tvAmTimeInit==null){
                        return;
                    }
                    if (reObject1.getString("success").equals("1")) {
                        //1成功0异常
                        MyToast.show("打卡成功");
                        yichangCd = "0";
                        waiqinCd = "0";
                        selectCurDakaInfo();
                    } else {
                        String initWaiqinCd = reObject1.getString("waiqinCd");
                        boolean edit = false;
                        if ("1".equals(initWaiqinCd)) {
                            edit = true;
                        }
                        new InitEditDialog(ClockInHomeActivity.this,
                                "提示", ClockInUtils.getClockInError(reObject1.getString("waiqinCd"), reObject1.getString("dakaType")), "确定", edit,
                                new StudyDialogListener() {
                                    @Override
                                    public void onStudyClick(String remark) {
                                        yichangCd = "1";
                                        if (initWaiqinCd.equals("1")) {
                                            waiqinCd = "1";
                                        } else {
                                            waiqinCd = "0";
                                        }
                                        insertDakaInfo(type, remark);
                                    }
                                }).show();
                    }
                } else {
                    MyToast.show(reObject.getString("msg"));
                }
            }

            @Override
            public void onError(String errorMsg) {
                dismissLoading();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        getworkList();
    }

    private void getworkList() {
        Map<String, String> map = new HashMap<>();
        //待审核 传0 已审核不传
        map.put("auditStatus", "0");
        map.put("pageNum", "1");
        map.put("pageSize", "1");
        // 1-新闻 2-视频 3-补卡 4-请假 5-外勤 6-图文
        map.put("type", "3,5");

        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<WorkNewEntity>>>() {
        }.getType(), null, Urls.selectKqMyWorkList, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<WorkNewEntity>>() {
            @Override
            public void onSuccess(List<WorkNewEntity> data) {
                if (ivAudit == null) {
                    return;
                }
                if (data != null && data.size() > 0) {
                    ivAudit.setVisibility(View.VISIBLE);
                } else {
                    ivAudit.setVisibility(View.GONE);
                }
            }

            @Override
            public void onError(String errorMsg) {
                if (ivAudit != null) {
                    ivAudit.setVisibility(View.GONE);
                }
            }
        });
    }

    private void getPermissions(int status) {
        XXPermissions.with(this)
                // 申请单个权限
                .permission(Permission.ACCESS_FINE_LOCATION)
                .permission(Permission.ACCESS_COARSE_LOCATION)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {
                            hasLocPermissions = true;
                            if (status != 0) {
                                //不是第一次定位 ，需要提示刷新
                                locationFlag = -1;
                                ivRefresh.startAnimation(rotate);
                            }
                            startLoc();
                        } else {
                            hasLocPermissions = false;
                            MyToast.show("定位权限未正常授予");
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        hasLocPermissions = false;
                        if (never) {
                            MyToast.show("被永久拒绝授权，请手动授予定位权限");
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(ClockInHomeActivity.this, permissions);
                        } else {
                            MyToast.show("获取定位权限失败");
                        }
                    }
                });
    }

    private void preData(int type) {
        //打卡前期处理
        if (type == 1) {
            if (Utils.isNull(tvAmTime.getText().toString())) {
                insertDakaInfo(1, "");
            } else {
                new InitDialog(ClockInHomeActivity.this,
                        "提示", "上班卡已打，确定更新打卡时间", "确定", true,
                        new ShareDialogListener() {
                            @Override
                            public void onClick() {
                                insertDakaInfo(1, "");
                            }
                        }).show();
            }
        } else {
            if (Utils.isNull(tvPmTime.getText().toString())) {
                insertDakaInfo(0, "");
            } else {
                new InitDialog(ClockInHomeActivity.this,
                        "提示", "下班卡已打，确定更新打卡时间", "确定", true,
                        new ShareDialogListener() {
                            @Override
                            public void onClick() {
                                insertDakaInfo(0, "");
                            }
                        }).show();
            }
        }
    }

    @OnClick({R.id.common_title_back, R.id.ll_record, R.id.ll_audit, R.id.ivHead, R.id.tvRules, R.id.tvProjectChoice, R.id.llRefresh, R.id.tvAmSure, R.id.tvPmSure})
    public void onClick(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.ll_record:
                //记录
                intent = new Intent(this, ClockInRecordActivity.class);
                startActivity(intent);
                break;
            case R.id.ll_audit:
                //审核
                intent = new Intent(this, AuditActivity.class);
                intent.putExtra("type", 3);
                startActivity(intent);
                break;
            case R.id.ivHead:
                break;
            case R.id.tvRules:
                //考勤规则
                if (clockInRulesEntity != null) {
                    String rulesTitle = clockInRulesEntity.getGroupName() + "(" + ClockInUtils.getGroupEnd(clockInRulesEntity.getGroupCode()) + ")";
                    new RulesDialog.Builder(this).setData(clockInRulesEntity, rulesTitle).show();
                }

                break;
            case R.id.tvProjectChoice:
                if (groupArray == null || groupEntities.size() == 0) {
                    MyToast.show("暂无可选项目组，请稍后重试");
                    return;
                }
                new XPopup.Builder(ClockInHomeActivity.this)
                        .maxWidth(Utils.dip2px(ClockInHomeActivity.this, 260))
                        .maxHeight(Utils.dip2px(ClockInHomeActivity.this, 300))
                        .asCenterList("请选择项目组", groupArray,
                                new OnSelectListener() {
                                    @Override
                                    public void onSelect(int position, String text) {
                                        groupCode = groupEntities.get(position).getGroupCode();
                                        tvProject.setText(text.replace("[常驻]","") + "(" + ClockInUtils.getGroupEnd(groupEntities.get(position).getGroupCode()) + ")");
                                    }
                                })
                        .show();

                break;
            case R.id.llRefresh:
                //地址刷新
                getPermissions(-1);
                break;
            case R.id.tvAmSure:
                //上午打卡
                if (Urls.antiShake.check()) {
                    return;
                }
//                if (ForbidVirtualLocation.isInstallVirtual(this) || isCheat) {
//                    MyToast.show("请先卸载虚拟定位软件后再打卡");
//                    return;
//                }
                if (!hasLocPermissions) {
                    MyToast.show("请先开启定位权限");
                    getPermissions(0);
                    return;
                }
                if ((System.currentTimeMillis() - locTime) > 10000) {
                    needType = 1;
                    startLoc();
                } else {
                    preData(1);
                }
                break;
            case R.id.tvPmSure:
                //下午打卡
                if (Urls.antiShake.check()) {
                    return;
                }
//                if (ForbidVirtualLocation.isInstallVirtual(this) || isCheat) {
//                    MyToast.show("请先卸载虚拟定位软件后再打卡");
//                    return;
//                }
                if (!hasLocPermissions) {
                    MyToast.show("请先开启定位权限");
                    getPermissions(0);
                    return;
                }
                if ((System.currentTimeMillis() - locTime) > 10000) {
                    needType = 0;
                    startLoc();
                } else {
                    preData(0);
                }
                break;
        }
    }

    private void startTimer() {
        if (mTimer == null) {
            mTimer = new Timer();
        }
        if (mTimerTask == null) {
            mTimerTask = new TimerTask() {
                @Override
                public void run() {
                    //每分中上传数据
                    Message message = new Message();
                    message.what = 1;
                    handler.sendMessage(message);
                }
            };
        }
        if (mTimer != null && mTimerTask != null) {
            mTimer.schedule(mTimerTask, 1000, 1000);//执行定时器中的任务
        }
    }

    // handler类接收数据
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                currentTime = currentTime + 1000;
                if (tvCurrentTime == null) {
                    return;
                }
                tvCurrentTime.setText(ClockInUtils.getCurrentTime2(currentTime));
            }
        }

    };
    private int locationFlag = 0;
    private boolean firstLocation=true;
    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location != null) {
                if (tvAmLoc == null || tvPmLoc == null) {
                    return;
                }
                if (Utils.isNull(location.getAddrStr())){
                    if(firstLocation){
                        if (mLocationClient != null) {
                            firstLocation=false;
                            mLocationClient.start();
                        }
                    }
                }
                if (!Utils.isNull(location.getAddrStr())) {
                    if (locationFlag == -1) {
                        MyToast.show("位置已刷新");
                    }
                    locationFlag++;
                    // 此定位点作弊概率，3代表高概率，2代表中概率，1代表低概率，0代表概率为0
                    KLog.i(locationFlag + location.getAddrStr() + location.getLongitude() + "==" + location.getLatitude() + "==" + location.getMockGnssProbability() + "=" + location.getProvince() + "==" + location.getCountry());
                    isCheat = false;
                    String addrStr = location.getAddrStr();
                    locAddress = addrStr.substring(location.getCountry().length(), addrStr.length());
                    new ShareUtils().putString(ClockInHomeActivity.this, StaticClass.LOC_ADDRESS, locAddress);
                    locWd = location.getLatitude() + "";
                    locJd = location.getLongitude() + "";
                    tvLoc.setText(locAddress);
                    locTime = System.currentTimeMillis();
                    if (needType >= 0) {
                        preData(needType);
                        needType = -1;
                    }
                }
                if (location.getLocType() == BDLocation.TypeOffLineLocation) {
                    // 离线定位成功  假设正常定位失败用离线数据
                    KLog.i("离线成功" + location.getLongitude() + "==" + location.getLatitude());
                    if (Utils.isNull(locWd) || Utils.isNull(locJd)) {
                        isCheat = false;
                        locWd = location.getLatitude() + "";
                        locJd = location.getLongitude() + "";
                        if (Utils.isNull(location.getAddrStr())) {
                            locAddress = new ShareUtils().getString(ClockInHomeActivity.this, StaticClass.LOC_ADDRESS, "未知");
                        } else {
                            locAddress = location.getAddrStr();
                        }
                        tvLoc.setText(locAddress);
                    }

                }
                if (locationFlag > 8) {
                    if (null != mLocationClient) {
                        locationFlag = 0;
                        if (mLocationClient != null) {
                            mLocationClient.stop();
                        }

                    }
                }
            }else {
            if(firstLocation){
                if (mLocationClient != null) {
                    firstLocation=false;
                    mLocationClient.start();
                }
            }
        }

        }
    }

    /**
     * 停止定时器，初始化定时器开关
     */
    private void stopTimer() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mLocationClient) {
            mLocationClient.stop();
        }
        if (rotate != null) {
            rotate.cancel();
        }
        stopTimer();
    }
}
